//
// Created by martin on 2/24/22.
//
#include "muduo/base/ThreadLocal.h"
#include "muduo/base/CurrentThread.h"
#include "muduo/base/Thread.h"

#include <stdio.h>

class Test : muduo::noncopyable
{
public:
    Test()
    {
        printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this);
    }
    ~Test()
    {
        printf("tid=%d, destructing %p %s\n", muduo::CurrentThread::tid(), this, name_.c_str());
    }

    const muduo::string& name() const { return name_; }
    void setName(const muduo::string& n) { name_ = n; }

private:
    muduo::string name_;
};

muduo::ThreadLocal<Test> t_testObj1;
muduo::ThreadLocal<Test> t_testObj2;

void print()
{
    printf("tid=%d, obj1 %p name=%s\n",
           muduo::CurrentThread::tid(),
           &t_testObj1.value(),
           t_testObj1.value().name().c_str());
    printf("tid=%d, obj2 %p name=%s\n",
           muduo::CurrentThread::tid(),
           &t_testObj2.value(),
           t_testObj2.value().name().c_str());
}

void threadFunc()
{
    print();
    t_testObj1.value().setName("changed 1");
    t_testObj2.value().setName("changed 2");
    print();
}

int main()
{
    t_testObj1.value().setName("main one");
    print();
    muduo::Thread t1(threadFunc);
    t1.start();
    t1.join();
    t_testObj2.value().setName("main two");
    print();
    return 0;
}